package com.example.rabbitmqextensions.controller;

import com.example.rabbitmqextensions.constant.Constants;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/producer")
public class ProducerController {
    @Resource(name = "rabbitTemplate")
    private RabbitTemplate rabbitTemplate;

    @Resource(name = "transactTemplate")
    private RabbitTemplate transactTemplate;

    // 死信+ttl 实现延时队列
    @RequestMapping("/delay")
    public String dlx() {
        rabbitTemplate.convertAndSend(Constants.NORMAL_EXCHANGE, "normal", "ttl test 30s..." + new Date(), messagePostProcessor -> {
            // 设置 30s 过期
            messagePostProcessor.getMessageProperties().setExpiration("30000");
            return messagePostProcessor;
        });
        rabbitTemplate.convertAndSend(Constants.NORMAL_EXCHANGE, "normal", "ttl test 10s..." + new Date(), messagePostProcessor -> {
            // 设置 10s 过期
            messagePostProcessor.getMessageProperties().setExpiration("10000");
            return messagePostProcessor;
        });
        return "发送成功";
    }

    // 事务
    @Transactional
    @RequestMapping("/trans")
    public String trans() {
        transactTemplate.convertAndSend("", Constants.TRANS_QUEUE, "trans test 1...");
        transactTemplate.convertAndSend("", Constants.TRANS_QUEUE, "trans test 2...");
        return "发送成功";
    }

    @RequestMapping("/qos")
    public String qos() {
        for (int i = 0; i < 20; i++) {
            rabbitTemplate.convertAndSend(Constants.QOS_EXCHANGE, "qos", "qos test ..." + i);
        }
        return "发送成功";
    }

    @RequestMapping("/quorum")
    public String quorum() {
        rabbitTemplate.convertAndSend("", Constants.QUORUM_QUEUE, "quorum test...");
        return "发送成功";
    }

    @RequestMapping("/cluster")
    public String cluster() {
        rabbitTemplate.convertAndSend("", Constants.QUORUM_QUEUE, "cluster test...");
        return "发送成功";
    }
}
